<template>
  <div style="width: 100%;height: 100%;">

    <Row :gutter="16">
      <Col :span="18">
        <div style="margin-bottom: 25px">
          <label>文章标题</label>
          <Input clearable
                 style="width: 70%;margin-left: 10px;"
                 type="text"
                 v-model="data.title"
                 icon="android-list"
                 @on-blur="handleArticletitleBlur"
                 placeholder="输入文章标题"/>
        </div>

        <div style="margin-bottom: 25px">
          <label style="margin-right: 10px">显示主图</label>
          <i-switch v-model="state.showSelectImg">
            <Icon type="android-done" slot="open"></Icon>
            <Icon type="android-close" slot="close"></Icon>
          </i-switch>

          <br/>
          <div v-show="state.showSelectImg">
            <img class="mainPic" :src="data.mainPic"/>
            <my-upload @onSuccess="uploadSuccess"></my-upload>
          </div>
        </div>

        <editor v-model="data.content" :init="tinymceInit"></editor>


      </Col>

      <Col :span="6">
        <Card dis-hover>
          <p slot="title">
            <Icon type="paper-airplane"></Icon>
            发布
          </p>

          <p style="margin-top: 10px">
            <Icon type="ios-calendar-outline"></Icon>&nbsp;&nbsp;
            <span v-if="state.publishTimeType === 'immediately'">立即发布</span><span
            v-else>定时：{{ data.publishTime }}</span>
            <Button v-show="!state.editPublishTime" size="small" @click="handleEditPublishTime" type="text">修改</Button>
            <transition name="publish-time">
              <div v-show="state.editPublishTime" class="publish-time-picker-con">
                <div style="margin-top: 10px">
                  <DatePicker @on-change="setPublishTime" type="datetime" style="width:200px;"
                              placeholder="选择日期和时间"></DatePicker>
                </div>
                <div style="margin-top: 10px">
                  <Button type="primary" @click="handleSavePublishTime">确认</Button>
                  <Button type="ghost" @click="cancelEditPublishTime">取消</Button>
                </div>
              </div>
            </transition>
          </p>

          <Row style="margin-top: 10px">
            <Button v-if="state.draftState" @click="handleSaveDraft" :loading="state.publishLoading">保存草稿</Button>
            <Button @click="handlePublish" :loading="state.publishLoading" icon="ios-checkmark" style="width:90px;"
                    type="primary">发布
            </Button>
          </Row>
        </Card>

        <div style="margin-top: 20px">
          <Card dis-hover>
            <p slot="title">
              <Icon type="navicon-round"></Icon>
              分类目录
            </p>

            <scroller-bar style="height: 200px;" scroll-y-type="inner">
              <RadioGroup v-model="data.sort" vertical style="padding: 5px">
                <Radio :label="item.value" v-for="item in state.sortList" :key="item.value">{{item.label}}</Radio>
              </RadioGroup>
            </scroller-bar>

          </Card>
        </div>

        <div style="margin-top: 20px">
          <Card dis-hover>
            <p slot="title">
              <Icon type="ios-pricetags-outline"></Icon>
              标签
            </p>

            <Row>
              <Col span="18">
                <Select v-model="data.articleTagSelected" filterable multiple @on-change="handleSelectTag"
                        placeholder="请选择文章标签">
                  <Option v-for="item in state.articleTagList" :value="item.value" :key="item.value">{{ item.label}}
                  </Option>
                </Select>
              </Col>
              <Col span="6" style="padding-left: 10px">
                <Button v-show="!state.addingNewTag" @click="handleAddNewTag" long type="ghost">新建</Button>
              </Col>
            </Row>
            <transition name="add-new-tag">
              <div v-show="state.addingNewTag" class="add-new-tag-con">
                <Col span="14">
                  <Input v-model="state.newTagName" placeholder="请输入标签名"/>
                </Col>
                <Col span="5" style="padding-left: 10px">
                  <Button @click="createNewTag" long type="primary">确定</Button>
                </Col>
                <Col span="5" style="padding-left: 10px">
                  <Button @click="cancelCreateNewTag" long type="ghost">取消</Button>
                </Col>
              </div>
            </transition>

          </Card>
        </div>
      </Col>
    </Row>

  </div>
</template>

<script>
  import tinymce from 'tinymce/tinymce'
  // import 'tinymce/themes/modern/theme'
  import 'tinymce/themes/silver'
  import 'tinymce/skins/ui/oxide/skin.css'

  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'

  import scrollerBar from '@/components/public/vue-scroller-bars';
  import MyUpload from '@/components/public/custom/ImgUpload.vue';
  import http from "../../axios/http";

  export default {
    name: "editComponent",
    components: {
      Editor,
      scrollerBar,
      MyUpload
    },
    data() {
      return {
        init: {
          requestUrl: '/push-article'
        },
        state: {
          showSelectImg: false,
          publishTimeType: 'immediately',
          editPublishTime: false, // 是否正在编辑发布时间
          publishLoading: false,
          articleTagList: [],  //小标签
          sortList: [], //分类集合数据
          addingNewTag: false,
          newTagName: '',
          draftState: true
        },
        data: {
          content: '',
          title: '',
          publishTime: '',
          mainPic: '',
          articleTagSelected: [],
          sort: ''
        },
        /**
         * 富文本编辑器的初始参数
         */
        tinymceInit: {
          language_url: 'static/tinymce/zh_CN.js',
          language: 'zh_CN',
          skin_url: 'static/tinymce/skins/lightgray',
          height: 500,
          plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
          toolbar:
            'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat',
          branding: false,
          images_upload_handler: (blobInfo, success, failure) => {
            this.handleImgUpload(blobInfo, success, failure);
          }
        }
      }
    },
    props: {
      id: {
        type: Number,
        default: -100
      }
    },
    created() {
      this.requestTagAllList();

      //请求分类目录的数据
      this.http.get('/get-sort-all', null, data => {
        let list = data.records;
        list.forEach(item => {
          this.state.sortList.push({
            value: item.sort.id,
            label: item.sort.name
          });
        });
      }, error => {
        this.$Message.error(error);
      });

      //这里如果是传入id则代表的是 更新文章
      if (this.id > 0) {
        this.state.draftState = false;
        this.init.requestUrl = "/update-article";
        this.http.post('/get-article-ids', {
          ids: JSON.stringify([this.id]),
          isSplit: false
        }, data => {
          let article = data.records[0].article;
          this.data.content = article.content;
          this.data.title = article.title;
          this.data.articleTagSelected = JSON.parse(article.tag);
          this.data.sort = article.rootsort;
          if (article.mainimg != null && article.mainimg.length != 0) {
            this.data.mainPic = article.mainimg;
            this.state.showSelectImg = true;
          }
        }, error => {
          this.$Message.error(error);
        })
      }
    },
    mounted() {
      tinymce.init({});
    },
    methods: {
      handleArticletitleBlur() {  //验证一下文章标题
        let title = this.data.title;
        if (title.length == 0) {
          this.$Message.error('文章标题不可为空哦');
        }
      },
      handleEditPublishTime() {
        this.state.editPublishTime = !this.state.editPublishTime;
      },
      setPublishTime(datetime) {
        this.data.publishTime = datetime;
      },
      handleSavePublishTime() {
        this.state.publishTimeType = 'timing';
        this.state.editPublishTime = false;
      },
      cancelEditPublishTime() {
        this.state.publishTimeType = 'immediately';
        this.state.editPublishTime = false;
      },
      handlePublish() {  //发布正文
        this.state.publishLoading = true;
        this.pushRequest(1);
        this.state.publishLoading = false;
      },
      handleSaveDraft() {  //发布为草稿箱
        this.state.publishLoading = true;
        this.pushRequest(0);
        this.state.publishLoading = false;
      },
      pushRequest(type) {   //发布文章的网络请求
        //发布文章的点击事件
        let data = this.data;
        if (this.state.showSelectImg) {
          if (data.mainPic.length == 0) {
            this.$Message.error("请上传主图");
            return;
          }
        }
        if (data.content.length == 0 || data.title.length == 0 ||
          data.sort.length == 0) {
          this.$Message.error("请填写必须输入的字段");
        } else {
          //表单验证成功 整理字段上传服务器
          let mainPic = '';
          if (this.state.showSelectImg) {
            mainPic = data.mainPic;
          }
          let original = {
            id: this.id,
            title: data.title,
            content: this.HTMLEncode(data.content),
            mainimg: mainPic,
            type: type,
            rootsort: data.sort,
            tag: data.articleTagSelected
          };
          let fromData;
          if (this.state.draftState) {
            fromData = {
              article: original,
              pushTime: null
            };
          } else {
            fromData = original;
          }
          this.http.postJson(this.init.requestUrl, fromData,
            success => {
              this.$Notice.success({
                title: '返回结果',
                desc: '文章成功发布！！！'
              });
              //清空操作
              this.data.content = '';
              this.data.title = '';
              this.data.mainPic = '';
              this.data.sort = '';
              this.data.articleTagSelected.length = 0;
              this.data.publishTime = '';
              this.state.showSelectImg = false;
              history.go(-1);
            }, error => {
              this.$Message.error(error);
            });
        }
      },
      handleSelectTag() {
        //tag 标签选择的时间  无用的方法  开发调试使用
      },
      handleAddNewTag() {
        this.state.addingNewTag = !this.state.addingNewTag;
      },
      createNewTag() {
        let self = this;
        if (this.state.newTagName != null && this.state.newTagName.length != 0) {
          this.http.get('/add-tag', {
            name: self.state.newTagName
          }, suc => {
            self.state.addingNewTag = false;
            self.state.newTagName = '';
            self.$Message.success("添加成功");
            this.requestTagAllList();
          }, error => {
            self.state.addingNewTag = false;
            self.state.newTagName = '';
            self.$Message.error(error);
          });
        } else {
          this.$Message.error('请输入标签名');
        }
      },
      /**
       * 请求标签数据所有的数据
       */
      requestTagAllList() {
        this.state.articleTagList.length = 0;
        this.http.get('/get-tag-all', null, data => {
          let list = data.records;
          list.forEach(item => {
            this.state.articleTagList.push({
              value: item.id,
              label: item.name
            });
          });
        }, error => {
          this.$Message.error(error);
        });
      },
      cancelCreateNewTag() {
        this.state.newTagName = '';
        this.state.addingNewTag = false;
      },
      uploadSuccess(url) {  //文件上传成功的时候
        this.data.mainPic = url;
      },
      /**
       * 编辑器文件上传
       * @param blobInfo
       * @param success
       * @param failure
       */
      handleImgUpload(blobInfo, success, failure) {
        let formdata = new FormData()
        formdata.set('file', blobInfo.blob());
        this.axios.post(this.baseUrl + '/upload', formdata).then(res => {
          if (res.data.code != 0) {
            success(res.data.data.absoluteUrl);
          } else {
            failure(res.data.msg);
          }

        }).catch(res => {
          failure('error')
        })
      },
      HTMLEncode(html) {
        let temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        let output = temp.innerHTML;
        temp = null;
        return output;
      }
    }
  }
</script>

<style lang="stylus" scoped>
  .mainPic
    max-width: 200px
    max-height: 250px
    margin-bottom: 8px

  .publish-time-picker-con
    margin-left: 40px
    padding-left: 10px
    height: 100px
    border-left: 1px dashed #ebe9f3
    overflow: hidden
</style>

<style lang="less" scoped>
  .publish-time-enter {
    height: 0;
  }

  .publish-time-enter-active, .publish-time-leave-active {
    transition: height .3s;
  }

  .publish-time-enter-to {
    height: 100px;
  }

  .publish-time-leave {
    height: 100px;
  }

  .publish-time-leave-to {
    height: 0;
  }

  .add-new-tag-con {
    margin-top: 20px;
    border-top: 1px dashed #dbdddf;
    padding: 20px 0;
    height: 60px;
    overflow: hidden;
  }

  .add-new-tag-enter {
    height: 0;
    margin-top: 0;
    padding: 0px 0;
  }

  .add-new-tag-enter-active, .add-new-tag-leave-active {
    transition: all .3s;
  }

  .add-new-tag-enter-to {
    height: 60px;
    margin-top: 20px;
    padding: 20px 0;
  }

  .add-new-tag-leave {
    height: 60px;
    margin-top: 20px;
    padding: 20px 0;
  }

  .add-new-tag-leave-to {
    height: 0;
    margin-top: 0;
    padding: 0px 0;
  }
</style>
